package cn.spark.study.core;

import org.apache.spark.Accumulator;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;

import java.util.Arrays;
import java.util.List;

/**
 * 累加变量
 *
 * @author jun.zhang6
 * @date 2020/11/6
 */
public class AccumulatorVariable {

    public static void main(String[] args) {
        SparkConf sparkConf = new SparkConf()
                .setAppName("AccumulatorVariable")
                .setMaster("local");

        JavaSparkContext sc = new JavaSparkContext(sparkConf);

        final Accumulator<Integer> accumulator = sc.accumulator(0);

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        JavaRDD<Integer> numbersRdd = sc.parallelize(numbers);

        numbersRdd.foreach(new VoidFunction<Integer>() {
            @Override
            public void call(Integer v) throws Exception {
                accumulator.add(v);
            }
        });

        System.out.println(accumulator.value());

        sc.close();
    }
}
